//
//  GameSetupViewController.m
//  fugitive
//
//  Created by Eugene Bistolas on 5/25/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "GameSetupViewController.h"


@implementation GameSetupViewController
@synthesize forwardGeocoder = forwardGeocoder_; 
@synthesize mapView = mapView_; 

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
   self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
   if (self) {
      // Custom initialization
      [[self navigationController] setNavigationBarHidden:YES animated:NO];
      loc = [[CLLocationManager alloc] init]; 
      loc.desiredAccuracy = kCLLocationAccuracyBest; 
      loc.delegate = self; 
      [loc startUpdatingLocation]; 
      isUp = NO; 
      self.title = @"Setup Game"; 
      isInStartMode = NO; 
      isInEndMode = NO; 
      nextValid = NO; 
      startPin = nil;
      stopPin = nil; 
      
      
   }
   return self;
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
   currLoc = newLocation.coordinate; 
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
   NSLog(@"GPS Error (manifested in Simulator)\n");
}


- (IBAction) startButton {
   if (startPin == nil) {
      [startButton setTitle:@"Reset start pin" forState:UIControlStateNormal]; 
   }
   BOOL wasToggled = NO; 
   if (isInEndMode) {
      isInEndMode = NO;
      UIImage *normalImg = [[UIImage imageNamed:@"white_normal.png"] stretchableImageWithLeftCapWidth:12 topCapHeight:0];
      [endButton setBackgroundImage:normalImg forState:UIControlStateNormal]; 
      wasToggled = YES; 
      [self animateViews:YES]; 
      
   }
   
   if (!isInStartMode) {
      isInStartMode = YES; 
      UIImage *activeImg = [[UIImage imageNamed:@"white_active.png"] stretchableImageWithLeftCapWidth:12 topCapHeight:0];
      [startButton setBackgroundImage:activeImg forState:UIControlStateNormal]; 
      if (wasToggled) {
         [self performSelector:@selector(searchbarDelay) withObject:nil afterDelay:0.3];
      }
      else {
         [self animateViews:NO]; 
         
      }
      
      if (startPin != nil) {
         [self.mapView removeAnnotation:startPin];
         startPin = nil; 
      }
      CLLocationCoordinate2D startCoord = CLLocationCoordinate2DMake(currLoc.latitude, (currLoc.longitude + 0.005)); 
      startPin = [[DDAnnotation alloc] initWithCoordinate:startCoord addressDictionary:nil];
      startPin.title = @"Start Location";
      startPin.subtitle = @"Use search or drag!"; 
      [self.mapView addAnnotation:startPin];
   }
   else {
      isInStartMode = NO; 
      UIImage *normalImg = [[UIImage imageNamed:@"white_normal.png"] stretchableImageWithLeftCapWidth:12 topCapHeight:0];
      [startButton setBackgroundImage:normalImg forState:UIControlStateNormal]; 
      [self animateViews:YES]; 
      
   }
   if (startPin != nil && stopPin != nil && !nextValid) {
      nextValid = YES; 
      [self animateButtonOrImage:BUTTON direction:LEFT tag:4 amount:350 speed:0.8];
   }
   [self.mapView selectAnnotation:startPin animated:YES];
   
}

- (IBAction) stopButton {
   if (stopPin == nil) {
      [endButton setTitle:@"Reset stop pin" forState:UIControlStateNormal]; 
   }
   BOOL wasToggled = NO; 
   self.searchDisplayController.searchBar.placeholder = nil; 
   if (isInStartMode) {
      isInStartMode = NO;
      UIImage *normalImg = [[UIImage imageNamed:@"white_normal.png"] stretchableImageWithLeftCapWidth:12 topCapHeight:0];
      [startButton setBackgroundImage:normalImg forState:UIControlStateNormal]; 
      wasToggled = YES; 
      [self animateViews:YES]; 
   }
   
   if (!isInEndMode) {
      isInEndMode = YES; 
      UIImage *activeImg = [[UIImage imageNamed:@"white_active.png"] stretchableImageWithLeftCapWidth:12 topCapHeight:0];
      [endButton setBackgroundImage:activeImg forState:UIControlStateNormal];
      if (wasToggled) {
         [self performSelector:@selector(searchbarDelay) withObject:nil afterDelay:0.3];
         
      }
      else {
         [self animateViews:NO]; 
      }
      if (stopPin != nil) {
         [self.mapView removeAnnotation:stopPin];
         stopPin = nil; 
      }
      CLLocationCoordinate2D stopCoord = CLLocationCoordinate2DMake(currLoc.latitude, (currLoc.longitude - 0.00005)); 
      stopPin = [[DDAnnotation alloc] initWithCoordinate:stopCoord addressDictionary:nil];
      stopPin.title = @"Stop Location";
      stopPin.subtitle = @"Use search or drag!"; 
      [self.mapView addAnnotation:stopPin];
      
      
   }
   else {
      isInEndMode = NO;
      UIImage *normalImg = [[UIImage imageNamed:@"white_normal.png"] stretchableImageWithLeftCapWidth:12 topCapHeight:0];
      [endButton setBackgroundImage:normalImg forState:UIControlStateNormal]; 
      [self animateViews:YES]; 
   }
   if (startPin != nil && stopPin != nil && !nextValid) {
      nextValid = YES; 
      [self animateButtonOrImage:BUTTON direction:LEFT tag:4 amount:350 speed:0.8];
   }
   [self.mapView selectAnnotation:stopPin animated:YES];
   
}

- (IBAction) backButton {
   [self.navigationController popToRootViewControllerAnimated:YES]; 
}

- (IBAction) nextButton {
   DurationViewController *dvc = [[DurationViewController alloc] initWithStartTarget:startPin.coordinate endTarget:stopPin.coordinate]; 
   [self.navigationController pushViewController:dvc animated:YES]; 
   [dvc release]; 
}

- (void) searchbarDelay {
   [self animateViews:NO]; 
}

- (void) introAnimation {
   pickImage.hidden = NO;
   yourImage.hidden = NO;
   pathImage.hidden = NO;
   [self animateInPick]; 
   [self performSelector:@selector(animateInYour) withObject:nil afterDelay:0.4];
   [self performSelector:@selector(animateInPath) withObject:nil afterDelay:0.8];
   [self performSelector:@selector(animateOutPick) withObject:nil afterDelay:1.5];
   [self performSelector:@selector(animateOutYour) withObject:nil afterDelay:2];
   [self performSelector:@selector(animateOutPath) withObject:nil afterDelay:2.5];
   [self performSelector:@selector(animateInButtons) withObject:nil afterDelay:3];
   
   
   
}

- (void) viewDidAppear:(BOOL)animated {
   [super viewDidAppear:animated]; 
   [self performSelector:@selector(introAnimation) withObject:nil afterDelay:0.4];
   
}

- (void) hideIntro {
   pickImage.hidden = YES;
   yourImage.hidden = YES;
   pathImage.hidden = YES; 
   [self animateButtonOrImage:BUTTON direction:DOWN tag:1 amount:350 speed:0.8];
   [self animateButtonOrImage:BUTTON direction:DOWN tag:2 amount:350 speed:0.8]; 
   [self animateButtonOrImage:BUTTON direction:LEFT tag:3 amount:350 speed:0.8]; 
   [self animateButtonOrImage:BUTTON direction:RIGHT tag:4 amount:350 speed:0.8];
   [self animateButtonOrImage:IMAGE direction:LEFT tag:1 amount:350 speed:0.8];
   [self animateButtonOrImage:IMAGE direction:LEFT tag:2 amount:350 speed:0.8]; 
   [self animateButtonOrImage:IMAGE direction:LEFT tag:3 amount:350 speed:0.8]; 
}

-(void) animateInPick {
   [self animateButtonOrImage:IMAGE direction:RIGHT tag:1 amount:350 speed:0.8];
}

-(void) animateInYour {
   [self animateButtonOrImage:IMAGE direction:RIGHT tag:2 amount:350 speed:0.8]; 
}

-(void) animateInPath {
   [self animateButtonOrImage:IMAGE direction:RIGHT tag:3 amount:350 speed:0.8]; 
}

-(void) animateOutPick {
   [self animateButtonOrImage:IMAGE direction:RIGHT tag:1 amount:350 speed:0.8];
}

-(void) animateOutYour {
   [self animateButtonOrImage:IMAGE direction:RIGHT tag:2 amount:350 speed:0.8]; 
}

-(void) animateOutPath {
   [self animateButtonOrImage:IMAGE direction:RIGHT tag:3 amount:350 speed:0.8]; 
}

-(void) animateInButtons {
   [self animateButtonOrImage:BUTTON direction:UP tag:1 amount:350 speed:0.8];
   [self animateButtonOrImage:BUTTON direction:UP tag:2 amount:350 speed:0.8]; 
   [self animateButtonOrImage:BUTTON direction:RIGHT tag:3 amount:350 speed:0.8];
}


//Forward geocoding code

- (void)forwardGeocoderFoundLocation:(BSForwardGeocoder*)geocoder
{
	if(forwardGeocoder.status == G_GEO_SUCCESS)
	{
		int searchResults = [forwardGeocoder.results count];
		
		// Add placemarks for each result
		for(int i = 0; i < searchResults; i++)
		{
			BSKmlResult *place = [forwardGeocoder.results objectAtIndex:i];
         
         if (isInStartMode) {
            if (startPin != nil) {
               [self.mapView removeAnnotation:startPin];
               startPin = nil; 
            }
            startPin = [[[DDAnnotation alloc] initWithCoordinate:place.coordinate addressDictionary:nil] autorelease];
            startPin.title = @"Start";
            startPin.subtitle = place.address;
            [self.mapView addAnnotation:startPin];
            [self.mapView selectAnnotation:[[self.mapView annotations] lastObject] animated:YES];
            
         }
         else if (isInEndMode) {
            if (stopPin != nil) {
               [self.mapView removeAnnotation:stopPin]; 
               stopPin = nil;
            }
            stopPin = [[[DDAnnotation alloc] initWithCoordinate:place.coordinate addressDictionary:nil] autorelease];
            stopPin.title = @"Stop";
            stopPin.subtitle = place.address;
            [self.mapView addAnnotation:stopPin];
            [self.mapView selectAnnotation:[[self.mapView annotations] lastObject] animated:YES];
            
         }
         
         
         
         
			
			NSArray *countryName = [place findAddressComponent:@"country"];
			if([countryName count] > 0)
			{
				NSLog(@"Country: %@", ((BSAddressComponent*)[countryName objectAtIndex:0]).longName );
			}
		}
		
		if([forwardGeocoder.results count] == 1)
		{
			BSKmlResult *place = [forwardGeocoder.results objectAtIndex:0];
			
			// Zoom into the location		
			[self.mapView setRegion:place.coordinateRegion animated:TRUE];
		}
		
		// Dismiss the keyboard
		[searchBar resignFirstResponder];
	}
	else {
		NSString *message = @"";
		
		switch (forwardGeocoder.status) {
			case G_GEO_BAD_KEY:
				message = @"The API key is invalid.";
				break;
				
			case G_GEO_UNKNOWN_ADDRESS:
				message = [NSString stringWithFormat:@"Could not find %@", forwardGeocoder.searchQuery];
				break;
				
			case G_GEO_TOO_MANY_QUERIES:
				message = @"Too many queries has been made for this API key.";
				break;
				
			case G_GEO_SERVER_ERROR:
				message = @"Server error, please try again.";
				break;
				
				
			default:
				break;
		}
		
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Information" 
                                                      message:message
                                                     delegate:nil 
                                            cancelButtonTitle:@"OK" 
                                            otherButtonTitles: nil];
		[alert show];
		[alert release];
	}
}

- (void)forwardGeocoderError:(BSForwardGeocoder*)geocoder errorMessage:(NSString *)errorMessage
{
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error!" 
                                                   message:errorMessage
                                                  delegate:nil 
                                         cancelButtonTitle:@"OK" 
                                         otherButtonTitles: nil];
	[alert show];
	[alert release];
	
}


//UISearchBar Delegate Code
- (void)searchBarSearchButtonClicked:(UISearchBar *)theSearchBar {
   
	NSLog(@"Searching for: %@", searchBar.text);
	if(forwardGeocoder == nil)
	{
		forwardGeocoder = [[BSForwardGeocoder alloc] initWithDelegate:self];
	}
	
	[forwardGeocoder findLocation:searchBar.text];
   
}

-(void)animateViews:(BOOL)moveup
{
   
   BOOL moved = NO;
   
	[UIView beginAnimations:nil context:nil];
	[UIView setAnimationDuration:0.3];
	
	for (UIView *view in [self.view subviews])
	{
      if ([view isKindOfClass:[UISearchBar class]]) {
         CGRect frame = view.frame;
         if(moveup && !isUp) {
            frame.origin.y -= 44;
            moved = YES;
         } else if (!moveup && isUp) {
            frame.origin.y += 44;
            moved = YES;
         }
         view.frame = frame;
      }
	}
	[UIView commitAnimations];
   if (moved)
      isUp = moveup;
}

//MKMapViewDelegate code
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>) annotation{
	
   if ([annotation isKindOfClass:[MKUserLocation class]]) {
      return nil;		
	}
	
	static NSString * const kPinAnnotationIdentifier = @"PinIdentifier";
	MKAnnotationView *draggablePinView = [self.mapView dequeueReusableAnnotationViewWithIdentifier:kPinAnnotationIdentifier];
	
	if (draggablePinView) {
		draggablePinView.annotation = annotation;
	} else {
		// Use class method to create DDAnnotationView (on iOS 3) or built-in draggble MKPinAnnotationView (on iOS 4).
		draggablePinView = [DDAnnotationView annotationViewWithAnnotation:annotation reuseIdentifier:kPinAnnotationIdentifier mapView:self.mapView];
      
		if ([draggablePinView isKindOfClass:[DDAnnotationView class]]) {
			// draggablePinView is DDAnnotationView on iOS 3.
		} else {
			// draggablePinView instance will be built-in draggable MKPinAnnotationView when running on iOS 4.
		}
	}		
	
	return draggablePinView;
}

// NOTE: DDAnnotationCoordinateDidChangeNotification won't fire in iOS 4, use -mapView:annotationView:didChangeDragState:fromOldState: instead.
- (void)coordinateChanged_:(NSNotification *)notification {
	
	DDAnnotation *annotation = notification.object;
	annotation.subtitle = [NSString	stringWithFormat:@"%f %f", annotation.coordinate.latitude, annotation.coordinate.longitude];
}

#pragma mark -
#pragma mark MKMapViewDelegate

- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)annotationView didChangeDragState:(MKAnnotationViewDragState)newState fromOldState:(MKAnnotationViewDragState)oldState {
	
	if (oldState == MKAnnotationViewDragStateDragging) {
		DDAnnotation *annotation = (DDAnnotation *)annotationView.annotation;
      annotation.subtitle = @"Use search or drag!";
	}
}


- (void) viewWillDisappear:(BOOL)animated {
   [super viewWillDisappear:animated]; 
   [[self navigationController] setNavigationBarHidden:YES animated:YES];
   
}

- (void) viewWillAppear:(BOOL)animated {
   [super viewWillAppear:animated];
   [[self navigationController] setNavigationBarHidden:YES animated:YES];
   [self hideIntro]; 
   MKCoordinateSpan span = MKCoordinateSpanMake(0.05, 0.05); 
   MKCoordinateRegion region = MKCoordinateRegionMake([loc location].coordinate, span);
   [self.mapView setRegion:region animated:NO]; 
   [self.mapView regionThatFits:region];
   [self animateViews:YES]; 
   
}



- (void)dealloc
{
   NSLog(@"Dealocing gsvc"); 
   self.mapView = nil; 
   [mapView_ release];
   [searchBar release];
   [loc release]; 
   
   [startButton release];
   [endButton release];
   [backButton release];
   [pickImage release];
   [yourImage release];
   [pathImage release];
   [nextButton release];
   [super dealloc];
}

- (void)didReceiveMemoryWarning
{
   // Releases the view if it doesn't have a superview.
   [super didReceiveMemoryWarning];
   
   // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
   [super viewDidLoad];
   // Do any additional setup after loading the view from its nib.
   self.mapView.delegate = self;
   searchBar.delegate = self;
   
   
   UIImage *normalImg = [[UIImage imageNamed:@"white_normal.png"] stretchableImageWithLeftCapWidth:12 topCapHeight:0];
   UIImage *activeImg = [[UIImage imageNamed:@"white_active.png"] stretchableImageWithLeftCapWidth:12 topCapHeight:0];
   [startButton setBackgroundImage:normalImg forState:UIControlStateNormal]; 
   [startButton setBackgroundImage:activeImg forState:UIControlStateHighlighted];
   [startButton setBackgroundImage:activeImg forState:UIControlStateSelected];
   [endButton setBackgroundImage:normalImg forState:UIControlStateNormal]; 
   [endButton setBackgroundImage:activeImg forState:UIControlStateHighlighted];
   [endButton setBackgroundImage:activeImg forState:UIControlStateSelected];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
   // Return YES for supported orientations
   return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(void)animateButtonOrImage:(int) type direction:(int) d tag:(int) t amount:(int) a speed:(double)s
{
	[UIView beginAnimations:nil context:nil];
	[UIView setAnimationDuration:s];
   [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut]; 
	
	for (UIView *view in [self.view subviews])
	{
      if ([view isKindOfClass:[UIButton class]] && type == BUTTON) {
         CGRect frame = view.frame;
         if (((UIButton*)view).tag == t) {
            if (d == UP) {
               frame.origin.y -= a; 
            }
            else if (d == DOWN) {
               frame.origin.y += a;
            }
            else if (d == LEFT) {
               frame.origin.x -= a;
            }
            else if (d == RIGHT) {
               frame.origin.x += a; 
            }
         }
         view.frame = frame;
      }
      else if ([view isKindOfClass:[UIImageView class]] && type == IMAGE) {
         CGRect frame = view.frame;
         if (((UIButton*)view).tag == t) {
            if (d == UP) {
               frame.origin.y -= a; 
            }
            else if (d == DOWN) {
               frame.origin.y += a;
            }
            else if (d == LEFT) {
               frame.origin.x -= a;
            }
            else if (d == RIGHT) {
               frame.origin.x += a; 
            }
         }
         view.frame = frame;
      }
	}
	[UIView commitAnimations];
}

- (void)viewDidUnload {
   endButton = nil;
   [startButton release];
   startButton = nil;
   [endButton release];
   endButton = nil;
   [backButton release];
   backButton = nil;
   [pickImage release];
   pickImage = nil;
   [yourImage release];
   yourImage = nil;
   [pathImage release];
   pathImage = nil;
   [nextButton release];
   nextButton = nil;
   [super viewDidUnload];
}
@end
